$(function () {
  $("#post_note form").submit(function () {
    var content = $.trim($("#post_note form textarea").val());
    var note;
    if (content) {
      var req = $.ajax({
        type: 'POST',
        timeout: 3,
        async: false,
        url: "/notes/api/note", 
        data: {'content': content},
        success: function (msg, status) {
          note = eval(msg)[0];
          alert(gettext("Your note have been published!"));
        },
        error: function (req, errmsg) {
          alert(gettext("There are some problems when posting note"));        
        }
      });
      $("#post_note form textarea").val("");
      // update the selected tab
      // This may by abruptly, but the elegance is too dear here
      var idx = $("#playground").tabs("option", "selected");
      if (idx != 2) { // bypass who's arround 
        var notes_e = $($("#playground > div.tab")[idx]).children(".notes");
        prepend_note(notes_e, note);
      }
    }
    return false;
  });
  $("#playground").tabs({
    show: function (event, ui) {
      if (/.*#me_fellows$/.test($(ui.tab).attr('href'))) {
        var notes_e = $(ui.panel).children(".notes");
        notes_e.text("");
        $(ui.panel).children("input:last").attr('disabled', '');        
        var ret = append_notes(notes_e, 10, Infinity, "/notes/api/me_fellows_notes");
        var notes_cnt = ret[0];
        var max_id = ret[1];        
        $("#playground #max_id").val(max_id); // set max_id
        if (notes_cnt < 10) { // if there's no more data 
          $(ui.panel).children("input:last").attr('disabled', 'disabled');
        }
        return;
      }
      if (/.*#universal$/.test($(ui.tab).attr('href'))) {
        var notes_e = $(ui.panel).children(".notes");
        notes_e.text("");
        $(ui.panel).children("input:last").attr('disabled', '');        
        var ret = append_notes(notes_e, 10, Infinity, "/notes/api/notes");
        $(ui.panel).children("input:last").attr('disabled', '');
        var notes_cnt = ret[0];
        var max_id = ret[1];
        $("#playground #max_id").val(max_id);  // set max_id
        if (notes_cnt < 10) { // if there's no more data 
          $(ui.panel).children("input:last").attr('disabled', 'disabled');
        }
        return;
      }
    }
  });
  $("#playground .load_more").click(function () {
    var idx = $("#playground").tabs("option", "selected");
    var notes_e = $($("#playground > div.tab")[idx]).children(".notes");
    var max_id = $("#playground #max_id").val(); 
    var ret = append_notes(notes_e, 10, max_id, "/notes/api/me_fellows_notes");
    var notes_cnt = ret[0];
    var max_id = ret[1];
    $("#playground #max_id").val(max_id);
    if (notes_cnt < 10) {
      $(this).attr('disabled', 'disabled');
    }
  });
  $("#post_note").max_length({max_length: 200});
});
